package com.starblink.store.discountproducts.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.FetchMerchantWebOnSaleProductsRecommendQuery
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.MerchantOnSaleRecommendProductQueryReq
import com.starblink.library.widget.sort.SortTypeEnum
import kotlinx.coroutines.launch

class StoreDiscountProductsVM : BaseViewModel() {
    //===页面传参数据Start
    var storeId: String = ""
    //===页面传参数据End

    // 排序方式： 0-默认排序 2-价格从高到低 3-价格从低到高 4-折扣从低到高 5-折扣从高到低
    var sortType: SortTypeEnum = SortTypeEnum.DEFAULT

    var curPageNo = 0
    private val listResponse: ListResponse = ListResponse()
    val listResponseLD: MutableLiveData<ListResponse> =
        MutableLiveData()

    class ListResponse {
        val totalList = ArrayList<ProductF?>() // 保存全部列表数据
        lateinit var pageList: List<ProductF?> // 保存单页请求数据
        var refresh: Boolean = true // true-下拉刷新，false表示加载更多
    }

    /**
     * 加载店铺折扣商品信息
     */
    fun loadSaleProducts(refresh: Boolean) {
        viewModelScope.launch {
            val requestPageNo = if (refresh) 1 else curPageNo + 1
            val result = SkGqlClient.skQuery(
                FetchMerchantWebOnSaleProductsRecommendQuery(
                    req = MerchantOnSaleRecommendProductQueryReq(
                        merchantWebNo = storeId,
                        pageNo = requestPageNo,
                        pageSize = 20,
                        sortType = sortType.code,
                        scene = 2  // 1-折扣好物模块 2-view more
                    )
                )
            )?.data?.fetchMerchantWebOnSaleProductsRecommend?.mapNotNull { it?.productF }

            if (result != null) {
                curPageNo = requestPageNo
                listResponse.apply {
                    pageList = result
                    this.refresh = refresh
                    if (this.refresh) {
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                listResponseLD.postValue(listResponse)
            }else{
                loadError(null)
            }
        }
    }
}